<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="/static/css/mini-nord.min.css">
  <title>Titbit Study Login</title>
  <style>

  </style>
</head>
<body>

  <div class="container">
    <div class="row">
      <div class="col-sm-1 col-md-2 col-lg-3"></div>
      <div class="col-sm-10 col-md-8 col-lg-6" style="padding:0.8rem;">

        <form onsubmit="login(this);return false;" autocomplete="off">
          <input type="text" name="username" oninput="cacheInput(this);" placeholder="用户名" required>
          <input type="password" name="passwd" oninput="cacheInput(this);" placeholder="密码" required>
          <input type="submit" value="登录">
        </form>
        <p style="text-align: center;">
          <a href="/" style="color:#4a4a4f;font-size:90%;">回到首页</a>
        </p>
        <div style="color:#676869;background-color: #dfdfdf;font-size:86;padding:1rem;margin:0.5rem;">
          login页面会检测是否登录，通过检测token是否存在，以及通过userinfo查看登录是否超时。注意查看页面中最开始的js代码。如果已经登录则会跳转到user页面。
        </div>
      </div>
      <div class="col-sm-1 col-md-2 col-lg-3"></div>
    </div>
  </div>
  <script>

    if (localStorage.getItem('token')) {
      try {
        let u = localStorage.getItem('userinfo')
        if (u) {
          let uinfo = JSON.parse(u)
          if (uinfo.expires + uinfo.time > Date.now()) {
            location.href = '/user'
          }
        }
      } catch(err) {
        console.error(err)
      }
    }

    let loginfo = {
      username : '',
      passwd : ''
    }

    function cacheInput (t) {
      if (t.name === 'username') {
        loginfo.username = t.value.trim()
      } else if (t.name === 'passwd') {
        loginfo.passwd = t.value
      }
    }

    function login(t) {
      if (loginfo.username === '' || loginfo.passwd === '') {
        return
      }

      fetch('/login', {
        method : 'POST',
        headers : {
          'content-type' : 'text/plain'
        },
        body : JSON.stringify(loginfo)
      }).then(async res => {

        if (!res.ok) {
          let errtext = await res.text()
          throw new Error(`${res.status} : ${errtext}`)
        } else {
          return res.json()
        }

      }).then(d => {
        
        localStorage.setItem('token', d.token)
        localStorage.setItem('userinfo', JSON.stringify(d.userinfo))
        
        location.href = '/user'

      }).catch(err => {
        alert(err.message)
      })

    }

  </script>
</body>
</html>
